<?php

namespace app\user\event\listeners\user;

use app\admin\model\finance\CreditConfig;
use app\user\logic\user\Account;
use app\user\logic\user\Credit as CreditLogic;
use app\user\logic\user\CreditFlow;

/**
 * 网页操作产生的积分
 */
class Credit
{
    public static function handle(Account $user)
    {
        // 参数
        $key = $user->credit_key;
        $mid = $user->id;
        $rel = $user->rel_pk;

        if (!$mid) return;
        // 获取注册积分规则
        $reg_score    = app(CreditConfig::class)->where('key', $key)->where('mhm_id', request()->mhm_id)->value('score');
        $invite_score = app(CreditConfig::class)->where('key', 'invite_register')->where('mhm_id', request()->mhm_id)->value('score');

        if ($reg_score) self::addCredit($mid, $reg_score, $rel, 'register');
        // Db::name('test')->save(['msg' => 'superior_user_id:'.$user->superior_user_id."，score:{$invite_score}"]);
        if ($user->superior_user_id && $invite_score) self::addCredit($user->superior_user_id, $invite_score, $rel, 'invite_register');
    }

    public static function addCredit($mid, $score, $rel, $key)
    {
        $conf   = self::conf();
        $re     = false;
        $credit = 0;
        // 添加积分
        $data = app(CreditLogic::class)->where('user_id', $mid)->findOrEmpty();
        if ($data->isEmpty()) {
            // 不存在就添加
            $data = CreditLogic::create([
                'user_id' => $mid,
                'credit'  => $score,
            ]);

            $re     = $data->isEmpty() ? 0 : 1;
            $credit = $score;
        } else if ($key != 'register') {
            // 存在就修改
            $data->credit += $score;
            $re           = $data->save();
            $credit       = $data->credit;
        }

        if ($re) {
            // 添加流水
            $create = [
                'user_id'  => $mid,
                'type'     => 4,
                'num'      => $score,
                'credit'   => $credit,
                'rel_type' => $key,
                'rel_pk'   => $rel,
                'note'     => $conf[$key] . '获得的积分',
            ];

            app(CreditFlow::class)::create($create);
        }
    }

    /**
     * 积分配置
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-08-27
     *
     * @return array [type] [description]
     */
    public static function conf(): array
    {
        return [
            'register'        => '注册',
            'invite_register' => '推荐注册',
            'sign_in'         => '签到',
            // 'course'            => '购买课程',
            // 'exams'             => '购买考试',
            // 'goods'             => '购买商品',
        ];
    }
}
